package com.study.javaFx.view;

import com.study.javaFx.model.MachineType;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class MachineTypeView {

    /**
     * 显示查询机型的窗口
     */
    public void showQueryWindow() {
        Stage stage = new Stage();
        stage.setTitle("查询机型");

        TableView<MachineType> table = new TableView<>();
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        TableColumn<MachineType, Number> idCol = new TableColumn<>("ID");
        idCol.setCellValueFactory(cellData -> cellData.getValue().typeIdProperty());

        TableColumn<MachineType, String> nameCol = new TableColumn<>("机型名称");
        nameCol.setCellValueFactory(cellData -> cellData.getValue().typeNameProperty());

        TableColumn<MachineType, String> specsCol = new TableColumn<>("规格");
        specsCol.setCellValueFactory(cellData -> cellData.getValue().specificationsProperty());

        TableColumn<MachineType, Number> rateCol = new TableColumn<>("费率/小时");
        rateCol.setCellValueFactory(cellData -> cellData.getValue().hourlyRateProperty());

        table.getColumns().addAll(idCol, nameCol, specsCol, rateCol);

        // 查询面板
        GridPane queryPane = new GridPane();
        queryPane.setPadding(new Insets(10));
        queryPane.setHgap(10);
        queryPane.setVgap(10);
        queryPane.add(new Label("输入机型ID:"), 0, 0);
        TextField idField = new TextField();
        queryPane.add(idField, 1, 0);
        Button queryBtn = new Button("查询");
        queryPane.add(queryBtn, 2, 0);

        // 查询按钮事件
        queryBtn.setOnAction(e -> {
            String idText = idField.getText().trim();
            if (idText.isEmpty()) {
                showAlert("请输入要查询的机型ID");
                return;
            }
            String BASE_URL = "http://localhost:8080/api/machineType";
            String url = BASE_URL + "/get/" + idText;
            java.net.http.HttpClient httpClient = java.net.http.HttpClient.newHttpClient();
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper().setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategies.SNAKE_CASE);
            java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder().uri(java.net.URI.create(url)).GET().build();
            httpClient.sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        System.out.println("后端返回原始数据: " + json); // 打印原始JSON
                        // 解析后端返回的Response<MachineType>
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        MachineType machineType = objectMapper.readValue(dataNode.traverse(), MachineType.class);
                        java.util.List<MachineType> types = new java.util.ArrayList<>();
                        if (machineType != null) types.add(machineType);
                        ObservableList<MachineType> data = FXCollections.observableArrayList(types);
                        javafx.application.Platform.runLater(() -> table.setItems(data));
                    } catch (Exception ex) {
                        System.out.println("JSON解析异常: " + ex.getMessage()); // 打印异常信息
                        javafx.application.Platform.runLater(() -> showAlert("解析数据失败: " + ex.getMessage()));
                    }
                })
                .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
        });

        // 初始加载全部机型数据
        String BASE_URL = "http://localhost:8080/api/machineType";
        java.net.http.HttpClient httpClient = java.net.http.HttpClient.newHttpClient();
        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper().setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategies.SNAKE_CASE);
        System.out.println("请求全部机型数据: " + BASE_URL + "/get");
        java.net.http.HttpRequest allRequest = java.net.http.HttpRequest.newBuilder().uri(java.net.URI.create(BASE_URL + "/get")).GET().build();
        httpClient.sendAsync(allRequest, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
            .thenApply(java.net.http.HttpResponse::body)
            .thenAccept(json -> {
                try {
                    System.out.println("后端返回原始数据: " + json); // 打印原始JSON
                    // 解析后端返回的Response<List<MachineType>>
                    com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                    com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                    java.util.List<MachineType> types = objectMapper.readValue(dataNode.traverse(), new com.fasterxml.jackson.core.type.TypeReference<java.util.List<MachineType>>(){});
                    ObservableList<MachineType> data = FXCollections.observableArrayList(types);
                    javafx.application.Platform.runLater(() -> table.setItems(data));
                } catch (Exception ex) {
                    System.out.println("JSON解析异常: " + ex.getMessage()); // 打印异常信息
                    javafx.application.Platform.runLater(() -> showAlert("初始化数据失败: " + ex.getMessage()));
                }
            })
            .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("初始化请求失败: " + ex.getMessage())); return null; });

        VBox vbox = new VBox(queryPane, table);
        vbox.setPadding(new Insets(10));
        Scene scene = new Scene(vbox, 500, 350);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示新增机型的窗口
     */
    public void showAddWindow() {
        Stage stage = new Stage();
        stage.setTitle("新增机型");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("名称:"), 0, 0);
        TextField nameField = new TextField();
        grid.add(nameField, 1, 0);
        grid.add(new Label("规格:"), 0, 1);
        ComboBox<String> specsCombo = new ComboBox<>();
        specsCombo.getItems().addAll(
            "CPU: Intel i7, RAM: 16GB",
            "CPU: Intel i5, RAM: 8GB",
            "CPU: Intel i3, RAM: 4GB"
        );
        grid.add(specsCombo, 1, 1);
        grid.add(new Label("费率/小时:"), 0, 2);
        ComboBox<Double> hourlyRateCombo = new ComboBox<>();
        for (double r = 0.5; r <= 3.0; r += 0.5) {
            hourlyRateCombo.getItems().add(r);
        }
        grid.add(hourlyRateCombo, 1, 2);

        Button submitBtn = new Button("提交");
        submitBtn.setOnAction(e -> {
            String name = nameField.getText().trim();
            String specs = specsCombo.getValue();
            Double hourlyRate = hourlyRateCombo.getValue();
            if (name.isEmpty() || specs == null || hourlyRate == null) {
                showAlert("请填写所有字段");
                return;
            }
            MachineType type = new MachineType(0, name, specs, hourlyRate);
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(type);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/machineType/add"))
                        .header("Content-Type", "application/json")
                        .POST(java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> javafx.application.Platform.runLater(() -> {
                            showInfoDialog("新增成功！");
                            stage.close();
                        }))
                        .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage());
            }
        });

        grid.add(submitBtn, 1, 3);
        Scene scene = new Scene(grid, 350, 200);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示修改机型的窗口
     */
    public void showUpdateWindow() {
        Stage stage = new Stage();
        stage.setTitle("修改机型");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("机型ID:"), 0, 0);
        ComboBox<Integer> idCombo = new ComboBox<>();
        grid.add(idCombo, 1, 0);
        grid.add(new Label("名称:"), 0, 1);
        TextField nameField = new TextField();
        grid.add(nameField, 1, 1);
        grid.add(new Label("规格:"), 0, 2);
        ComboBox<String> specsCombo = new ComboBox<>();
        specsCombo.getItems().addAll(
            "CPU: Intel i7, RAM: 16GB",
            "CPU: Intel i5, RAM: 8GB",
            "CPU: Intel i3, RAM: 4GB"
        );
        grid.add(specsCombo, 1, 2);
        grid.add(new Label("费率/小时:"), 0, 3);
        ComboBox<Double> hourlyRateCombo = new ComboBox<>();
        for (double r = 0.5; r <= 3.0; r += 0.5) {
            hourlyRateCombo.getItems().add(r);
        }
        grid.add(hourlyRateCombo, 1, 3);

        Button submitBtn = new Button("提交");
        submitBtn.setDisable(true);

        // 异步加载所有机型ID
        java.net.http.HttpRequest allReq = java.net.http.HttpRequest.newBuilder()
                .uri(java.net.URI.create("http://localhost:8080/api/machineType/get"))
                .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(allReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        java.util.Set<Integer> ids = new java.util.HashSet<>();
                        for (com.fasterxml.jackson.databind.JsonNode type : dataNode) {
                            if (type.has("typeId")) ids.add(type.get("typeId").asInt());
                        }
                        javafx.application.Platform.runLater(() -> {
                            idCombo.getItems().setAll(ids);
                            if (!ids.isEmpty()) submitBtn.setDisable(false);
                        });
                    } catch (Exception ex) {
                        javafx.application.Platform.runLater(() -> showAlert("加载机型ID失败: " + ex.getMessage()));
                    }
                });

        idCombo.setOnAction(e -> {
            Integer selectedId = idCombo.getValue();
            if (selectedId == null) return;
            // 查找已加载的机型数据
            String BASE_URL = "http://localhost:8080/api/machineType";
            java.net.http.HttpClient httpClient = java.net.http.HttpClient.newHttpClient();
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper().setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategies.SNAKE_CASE);
            String url = BASE_URL + "/get/" + selectedId;
            java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder().uri(java.net.URI.create(url)).GET().build();
            httpClient.sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        MachineType machineType = objectMapper.readValue(dataNode.traverse(), MachineType.class);
                        if (machineType != null) {
                            javafx.application.Platform.runLater(() -> {
                                nameField.setText(machineType.getTypeName());
                                specsCombo.setValue(machineType.getSpecifications());
                                hourlyRateCombo.setValue(machineType.getHourlyRate());
                            });
                        }
                    } catch (Exception ex) {
                        javafx.application.Platform.runLater(() -> showAlert("加载机型数据失败: " + ex.getMessage()));
                    }
                })
                .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
        });

        submitBtn.setOnAction(e -> {
            Integer id = idCombo.getValue();
            String name = nameField.getText().trim();
            String specs = specsCombo.getValue();
            Double hourlyRate = hourlyRateCombo.getValue();
            if (id == null || name.isEmpty() || specs == null || hourlyRate == null) {
                showAlert("请填写所有字段");
                return;
            }
            MachineType type = new MachineType(id, name, specs, hourlyRate);
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(type);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/machineType/update"))
                        .header("Content-Type", "application/json")
                        .PUT(java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> javafx.application.Platform.runLater(() -> {
                            showInfoDialog("修改成功！");
                            stage.close();
                        }))
                        .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage());
            }
        });

        grid.add(submitBtn, 1, 4);
        Scene scene = new Scene(grid, 350, 250);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示删除机型的窗口
     */
    public void showDeleteWindow() {
        Stage stage = new Stage();
        stage.setTitle("删除机型");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("机型ID:"), 0, 0);
        ComboBox<Integer> idCombo = new ComboBox<>();
        grid.add(idCombo, 1, 0);

        Button submitBtn = new Button("删除");
        submitBtn.setDisable(true);

        // 异步加载所有机型ID
        java.net.http.HttpRequest allReq = java.net.http.HttpRequest.newBuilder()
                .uri(java.net.URI.create("http://localhost:8080/api/machineType/get"))
                .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(allReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        java.util.List<Integer> ids = new java.util.ArrayList<>();
                        for (com.fasterxml.jackson.databind.JsonNode type : dataNode) {
                            ids.add(type.get("typeId").asInt());
                        }
                        javafx.application.Platform.runLater(() -> {
                            idCombo.getItems().setAll(ids);
                            if (!ids.isEmpty()) submitBtn.setDisable(false);
                        });
                    } catch (Exception ex) {
                        javafx.application.Platform.runLater(() -> showAlert("加载机型ID失败: " + ex.getMessage()));
                    }
                });

        submitBtn.setOnAction(e -> {
            Integer id = idCombo.getValue();
            if (id == null) {
                showAlert("请选择要删除的机型ID");
                return;
            }
            MachineType type = new MachineType();
            type.setTypeId(id);
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(type);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/machineType/delete"))
                        .header("Content-Type", "application/json")
                        .method("DELETE", java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> javafx.application.Platform.runLater(() -> {
                            showInfoDialog("删除成功！");
                            stage.close();
                        }))
                        .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage())); return null; });
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage());
            }
        });

        grid.add(submitBtn, 1, 1);
        Scene scene = new Scene(grid, 350, 150);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示错误弹窗
     */
    private void showAlert(String msg) {
        javafx.application.Platform.runLater(() -> new Alert(Alert.AlertType.ERROR, msg).showAndWait());
    }

    /**
     * 显示标准信息弹窗
     * @param msg 提示信息
     */
    private void showInfoDialog(String msg) {
        javafx.application.Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText(null);
            alert.setContentText(msg);
            alert.showAndWait();
        });
    }
} 